﻿using AutoMapper;
using MediatR;
using RedDragon.Common.Domain.MaterialManagements;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.MaterialManagements
{
    /// <summary>
    /// 物料单位显示Handler
    /// </summary>
    public class SearchMaterialUnitHandler : IRequestHandler<SearchMaterialUnitCommand, Result>
    {
        /// <summary>
        /// mapper
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 物料单位表仓储
        /// </summary>
        public readonly IBaseRepository<MaterialUnit> materialUnitrepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchMaterialUnitHandler> logger;
        /// <summary>
        /// 物料单位 
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="materialUnitrepository"></param>
        /// <param name="logger"></param>
        public SearchMaterialUnitHandler(IMapper mapper, IBaseRepository<MaterialUnit> materialUnitrepository, ILogger<SearchMaterialUnitHandler> logger)
        {
            this.mapper = mapper;
            this.materialUnitrepository = materialUnitrepository;
            this.logger = logger;
        }
        /// <summary>
        /// 物料单位
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(SearchMaterialUnitCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                var materialUnit = await(await materialUnitrepository.GetAll()).ToListAsync();
                //判断获取的数据不为空
                if (materialUnit.Count > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = materialUnit;
                    result.Msg = "物料单位显示查询成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = " 物料单位显示查询失败" + ex.Message;
                logger.LogError(" 物料单位显示查询失败" + ex.Message);
                throw;
            }
            return result;
        }
    }
}
